package com.zn.task;

import com.alibaba.fastjson.JSONObject;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;
import com.zn.asycn.CalculateKLineExecutor;
import com.zn.socketReceiver.ReaderTask;
import com.zn.util.Constant;
import com.zn.util.DateUtils;
import com.zn.util.UUIDUtils;
import com.zn.vo.HyDate;
import com.zn.vo.Target;
import com.zn.web.rpc.MdRemoteCall;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author YinJiaWei
 * @version 2018/11/4 12:20
 */
@Component
public class ExecuteCSVTask {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private CalculateKLineExecutor calculateKLineExecutor;
    @Autowired
    private MdRemoteCall mdRemoteCall;

    //每1秒执行一次
//    @Scheduled(cron="*/1 * * * * ?")
    public void writeCSVContent(){
        System.err.println("writeContent....start...............");
        String nowDate=DateUtils.convertDateToString(new Date());
        String filePath = "D:\\项目设计\\融资融券\\csvFile\\order_"+nowDate+".csv";
        // 创建CSV写对象
        try {
            // 写表头
            File file = new File(filePath);
            if(!file.exists()){
                CsvWriter csvWriter = new CsvWriter(filePath,',', Charset.forName("GBK"));
                //写头列
                String[] headers = {"编号","姓名","年龄"};
                csvWriter.writeRecord(headers);
                csvWriter.close();
            }else{
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath,true),"GBK"),1024);
                CsvWriter csvWriter =  new CsvWriter(out,',');
                String[] content = {String.valueOf(UUIDUtils.getMathRandom()),productName(), String.valueOf((Math.random()*90+10))};
                csvWriter.writeRecord(content);
                csvWriter.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }

    /**
     * 委托响应
     */
//    @Scheduled(cron="*/5 * * * * ?")
    public void readCSVContent() {
        try {
            System.err.println("readCSVContent....start...............");
            String nowDate=DateUtils.convertDateToString(new Date());
            String filePath = "D:\\results\\";
            String fileName="result_order."+DateUtils.getDateTime("yyyyMMdd", new Date())+".csv";
            File file = new File(filePath);
            if(!file.exists()){
                return;
            }
            /**filepath是文件全路径*/
            CsvReader cr = new CsvReader(filePath+fileName, ',', Charset.forName("GBK"));
            cr.readHeaders();
            /**用来保存数据*/
            ArrayList<String[]> csvList = new ArrayList<String[]>();
            /**文件数据的下标**/
            int dataIndex = 0;
            /**从多少行开始读**/
            int readIndex = 0;
            String redisReadIndex=redisTemplate.opsForValue().get("readIndex");
            if(StringUtils.isNotBlank(redisReadIndex)){
                readIndex=Integer.valueOf(redisReadIndex);
            }
            while (cr.readRecord()) {
                if (dataIndex >= readIndex) {
                    System.err.println("getRawrecord............" + cr.getRawRecord());
                    csvList.add(cr.getValues());
                }
                dataIndex++;
            }
            System.err.println("dataIndex:"+readIndex);
            redisTemplate.opsForValue().set("readIndex", String.valueOf(dataIndex));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    private String productName(){
        char str1= (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
        char str2= (char) (0x4e00 + (int) (Math.random() * (0x9fa5 - 0x4e00 + 1)));
        return str1+""+str2;
    }
    @Scheduled(cron="0 36 15 * * ?")
    public void readFile() {
        try {
            FileInputStream fis = new FileInputStream("C:\\Users\\yinji\\Desktop\\tick\\10001557-tick.log");

            //Construct BufferedReader from InputStreamReader
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            ReaderTask readerTask=new ReaderTask(null,redisTemplate,mongoTemplate,mdRemoteCall,calculateKLineExecutor);
            String line = null;
            while ((line = br.readLine()) != null) {
//                System.out.println(line);
                Thread.sleep(100);
                readerTask.parseDataItem(line);
            }

            br.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
